package com.cjm.algorithm.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


public class Ti40 {
    public static void main(String[] args) {
        Ti40 ti40 = new Ti40();
        ti40.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8);
    }


    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        boolean[] dup = new boolean[candidates.length];
        method(candidates, target, 0, 0, dup);
        return res;
    }

    private List<List<Integer>> res = new ArrayList<>();
    private LinkedList<Integer> path = new LinkedList<>();

    private void method(int[] candidates, int target, int startIndex, int sum, boolean[] dup) {
        if (target == sum) {
            res.add(new ArrayList<>(path));
            return;
        }
        if (sum > target) {
            return;
        }

        for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1] && !dup[i - 1]) {
                continue;
            }
            sum += candidates[i];
            dup[i] = true;
            path.addFirst(candidates[i]);
            method(candidates, target, i + 1, sum, dup);
            sum -= candidates[i];
            path.removeFirst();
            dup[i] = false;
        }
    }
}
